﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Net.SourceForge.Vietpad.InputMethod;
using System.Text.RegularExpressions;
using System.Security.Permissions;
using System.IO;//for javascript run on form1

namespace DBA.App.Dictionary
{
    
    //for javascript run on form1////////////////
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    //////////////////////////////////////
   
    public partial class Form1 : Form
    {
        private String strIndexFile = Application.StartupPath+ @"\dict\en-vi.index";
        private String strDictFile = Application.StartupPath + @"\dict\en-vi.dict";
        private bool blnEnableVietPad = false;
        private System.Speech.Synthesis.SpeechSynthesizer synth= new System.Speech.Synthesis.SpeechSynthesizer(); 
        public Form1()
        {
            InitializeComponent();
            webBrowser1.Url = new Uri(@"about:blank");
            webBrowser1.IsWebBrowserContextMenuEnabled = false;
            webBrowser1.WebBrowserShortcutsEnabled = false;
            webBrowser1.AllowWebBrowserDrop = false;
            webBrowser1.ObjectForScripting = this;
            // ignore error script
            webBrowser1.ScriptErrorsSuppressed = true;

        }

        public void Pronounce() 
        {
            if (!cmbWord.Text.Equals(""))
            {
                synth.SpeakAsync(cmbWord.Text);
            }
        }
       
        private void btnSearch_Click(object sendaer, EventArgs e)
        {
            string strStartupPath1 = Application.StartupPath;
            string strStartupPath= strStartupPath1.Replace("\\", "/").Replace(" ", "%20");
            string strWord = cmbWord.Text.Trim();
            if (strWord == "")
                return; 
            string strLookupResult = Dictionary.LookUp(strWord);
            string strButtonSpell = @"&nbsp; <input src=file:///" + strStartupPath + "/speak2.PNG type=image width=18 height=18  onclick=\"window.external.Pronounce()\" />";
            string strHeaderResult = "<li style='list-style:none; padding-left:0px'><b>" + strWord + "</b>" + strButtonSpell + "</li><br/>";
            // set style for content result
            strLookupResult = strLookupResult.Replace("+", ":")
                 .Replace("=", "#")
                 .Replace("@", "</li><li  style='list-style:none; padding-left:0px;color:brown'>")              //word                 
                 .Replace("*", "</li><li  style='list-style:disc ; padding-left:20px;color:blue'>")     //từ loại
                 .Replace("- ", "</li><li  style='list-style:circle; padding-left:40px'>")  //định nghĩa    
                 .Replace("!", "</li><li  style='list-style:none; padding-left:30px;color:red'>")  //thành ngữ
                 .Replace("#", "</li><li  style='list-style:square; padding-left:50px;;color:green'>") + "</li></ul>";//đồng nghĩa
           // clear screen
            webBrowser1.DocumentText = "";
            System.Windows.Forms.Application.DoEvents();
            //display header, content
            webBrowser1.Document.Write(strHeaderResult);
            webBrowser1.Document.Write(strLookupResult);
            System.Windows.Forms.Application.DoEvents();
            //display image
            string strImageUrl = strStartupPath1 +  @"\image\" + strWord + ".jpg";
            //check file if exist
            if (!File.Exists(strImageUrl))
            {
                string strNewImageUrl = "";
                //check internet connection
                if (GoogleImager.IsConnectedToInternet())
                {
                    //check server if operate                    
                    if (GoogleImager.IsServerActive())
                    {
                        strNewImageUrl = GoogleImager.GetImageUrl(cmbWord.Text);
                        GoogleImager.Save(strNewImageUrl, strImageUrl);
                    }
                    else
                    {
                        strImageUrl = strStartupPath1 + @"\image\";
                    }
                    
                }
                else
                {
                    strImageUrl = strStartupPath1 + @"\image\";
                }                             
                              
            }
                        
            webBrowser1.Document.Write("<div><img src=" +@"file:///" + strImageUrl.Replace(" ", "%20")  + " /></div> ");


            //store historry
            SaveHistory();
        }


        public void SaveHistory()
        {
            int count = cmbWord.Items.Count;       
            int i=0;
            for(; i < count; i++){
                if (String.Compare(cmbWord.Items[i].ToString(), cmbWord.Text) == 0)
                {
                    i = count;
                }
                
                
            }
            if(i!=count+1)
            {
                cmbWord.Items.Insert(0,cmbWord.Text);
            }
            
        }


        public void RemoveHistory()
        {
            int count = cmbWord.Items.Count;
            if (count > 1)
                if (cmbWord.SelectedIndex == count - 1)
                {
                    cmbWord.Items.Clear();
                    cmbWord.Items.Add("");
                    cmbWord.Items.Add("Clear History");
                    cmbWord.Text = "";
                }
            
        }        

        private void cmbWord_TextChanged(object sender, EventArgs e)
        {
            if (!cmbWord.Text.Equals(""))
            {
                AutoCompleteStringCollection wordcollection = new AutoCompleteStringCollection();
                wordcollection.AddRange((String[]) Dictionary.getNearestWord(cmbWord.Text).ToArray(typeof(String)));
                cmbWord.AutoCompleteCustomSource = wordcollection;
                cmbWord.SelectionStart = cmbWord.Text.Length;
                System.Windows.Forms.Application.DoEvents();
            }
            
        }

        private void cmbWord_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !cmbWord.Text.Equals(""))
            {
                btnSearch_Click(sender, e);               
            }
        }

        private void btnSound_Click(object sender, EventArgs e)
        {
           
                if (!cmbWord.Text.Equals(""))
                {
                    synth.SpeakAsync(cmbWord.Text);
                }
           
        }

      

        private void cmbWord_DropDownClosed(object sender, EventArgs e)
        {
            RemoveHistory();
        }

        private void Form1_Load(object sender, EventArgs e)
        {               
            //load data for cmbDictionary
            DataSet ds= XMLer.GetDictionary();
            cmbDictionary.DataSource = ds.Tables["Dictionary"];
            cmbDictionary.DisplayMember = "name";
            cmbDictionary.ValueMember = "id";
            Dictionary.LoadIndexFile();
            //set focus cmbWord to lookup
            cmbWord.Focus();
            cmbWord.Select();
            //vietpad
            TextBoxBase textComp = new TextBox();
            VietKeyHandler keyHandler = new VietKeyHandler(textComp);
            textComp.KeyPress += new KeyPressEventHandler(keyHandler.OnKeyPress);
            VietKeyHandler.InputMethod = InputMethods.VNI;  //có thể sử dụng kiểu telex vni hoặc viqr
            VietKeyHandler.VietModeEnabled = false;
            VietKeyHandler.SmartMark = true;
            cmbWord.KeyPress += new KeyPressEventHandler(new VietKeyHandler(cmbWord).OnKeyPress);
       
           
        }

       

        

        private void btnTranslateText_Click(object sender, EventArgs e)
        {
            if (GoogleTranslater.IsConnectedToInternet() && GoogleTranslater.IsServerActive())
            {
                Form2 frm2 = new Form2();
                frm2.ShowDialog();
            }
            else
            {
                MessageBox.Show("Disconnected from internet. Cannot use this function");
            }
        }

        private void cmbWord_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void cmbDictionary_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Dictionary.isloaded)
            {
                Dictionary.strIndexFile = Application.StartupPath + @"\dict\" + cmbDictionary.SelectedValue.ToString() + ".index";
                Dictionary.strDictFile = Application.StartupPath + @"\dict\" + cmbDictionary.SelectedValue.ToString() + ".dict";
                Dictionary.ReLoadIndexFile();
            }                                                                                        
                                                                                                              
        }

     

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (blnEnableVietPad)
            {
                VietKeyHandler.VietModeEnabled = false;
                this.button1.Image = global::DBA.App.Dictionary.Properties.Resources.eng;               
                blnEnableVietPad = false;
                this.button1.ContextMenuStrip = null;
            }
            else
            {
                VietKeyHandler.VietModeEnabled = true;
                this.button1.Image = global::DBA.App.Dictionary.Properties.Resources.viet1;
                blnEnableVietPad = true;
                this.button1.ContextMenuStrip = this.contextMenuStrip1;
            }
        }

        private void vNIToolStripMenuItem_Click(object sender, EventArgs e)
        {
            VietKeyHandler.InputMethod = InputMethods.VNI;
            
        }

        private void telexToolStripMenuItem_Click(object sender, EventArgs e)
        {
            VietKeyHandler.InputMethod = InputMethods.Telex;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            frmSettings frmSettings = new frmSettings();
            frmSettings.ShowDialog();
        }

        

     

       

       

       
    }
}
